{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_m8ksq1l",
    "id": "ECBDC362D7D147C888F06244BC276561",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 循环神经网络\n",
    "本节介绍循环神经网络，下图展示了如何基于循环神经网络实现语言模型。我们的目的是基于当前的输入与过去的输入序列，预测序列的下一个字符。循环神经网络引入一个隐藏变量$H$，用$H_{t}$表示$H$在时间步$t$的值。$H_{t}$的计算基于$X_{t}$和$H_{t-1}$，可以认为$H_{t}$记录了到当前字符为止的序列信息，利用$H_{t}$对序列的下一个字符进行预测。\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jkm0v44i.png?imageView2/0/w/640/h/640)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1501E9868E46429286E75AC573A894DD",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 循环神经网络的构造\n",
    "\n",
    "我们先看循环神经网络的具体构造。假设$\\boldsymbol{X}_t \\in \\mathbb{R}^{n \\times d}$是时间步$t$的小批量输入，$\\boldsymbol{H}_t  \\in \\mathbb{R}^{n \\times h}$是该时间步的隐藏变量，则：\n",
    "\n",
    "\n",
    "$$\n",
    "\\boldsymbol{H}_t = \\phi(\\boldsymbol{X}_t \\boldsymbol{W}_{xh} + \\boldsymbol{H}_{t-1} \\boldsymbol{W}_{hh}  + \\boldsymbol{b}_h).\n",
    "$$\n",
    "\n",
    "\n",
    "其中，$\\boldsymbol{W}_{xh} \\in \\mathbb{R}^{d \\times h}$，$\\boldsymbol{W}_{hh} \\in \\mathbb{R}^{h \\times h}$，$\\boldsymbol{b}_{h} \\in \\mathbb{R}^{1 \\times h}$，$\\phi$函数是非线性激活函数。由于引入了$\\boldsymbol{H}_{t-1} \\boldsymbol{W}_{hh}$，$H_{t}$能够捕捉截至当前时间步的序列的历史信息，就像是神经网络当前时间步的状态或记忆一样。由于$H_{t}$的计算基于$H_{t-1}$，上式的计算是循环的，使用循环计算的网络即循环神经网络（recurrent neural network）。\n",
    "\n",
    "在时间步$t$，输出层的输出为：\n",
    "\n",
    "\n",
    "$$\n",
    "\\boldsymbol{O}_t = \\boldsymbol{H}_t \\boldsymbol{W}_{hq} + \\boldsymbol{b}_q.\n",
    "$$\n",
    "\n",
    "\n",
    "其中$\\boldsymbol{W}_{hq} \\in \\mathbb{R}^{h \\times q}$，$\\boldsymbol{b}_q \\in \\mathbb{R}^{1 \\times q}$。\n",
    "\n",
    "\n",
    "## 从零开始实现循环神经网络\n",
    "\n",
    "我们先尝试从零开始实现一个基于字符级循环神经网络的语言模型，这里我们使用周杰伦的歌词作为语料，首先我们读入数据："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "graffitiCellId": "id_uso50ly",
    "id": "20171E08BC064A1DA6315C234E0EDF33",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import time\n",
    "import math\n",
    "import sys\n",
    "sys.path.append(\"/home/kesci/input\")\n",
    "import d2l_jay9460 as d2l\n",
    "(corpus_indices, char_to_idx, idx_to_char, vocab_size) = d2l.load_data_jay_lyrics()\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_kryzk9x",
    "id": "797F389C048341748C8B9D95206722C6",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### one-hot向量\n",
    "\n",
    "我们需要将字符表示成向量，这里采用one-hot向量。假设词典大小是$N$，每次字符对应一个从$0$到$N-1$的唯一的索引，则该字符的向量是一个长度为$N$的向量，若字符的索引是$i$，则该向量的第$i$个位置为$1$，其他位置为$0$。下面分别展示了索引为0和2的one-hot向量，向量长度等于词典大小。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "graffitiCellId": "id_vljucfa",
    "id": "0A8DFF6F37CA40C1B87AAF9D0D361497",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[1., 0., 0.,  ..., 0., 0., 0.],\n",
      "        [0., 0., 1.,  ..., 0., 0., 0.]])\n",
      "torch.Size([2, 1027])\n",
      "tensor([1., 1.])\n"
     ]
    }
   ],
   "source": [
    "def one_hot(x, n_class, dtype=torch.float32):\n",
    "    result = torch.zeros(x.shape[0], n_class, dtype=dtype, device=x.device)  # shape: (n, n_class)\n",
    "    result.scatter_(1, x.long().view(-1, 1), 1)  # result[i, x[i, 0]] = 1\n",
    "    return result\n",
    "    \n",
    "x = torch.tensor([0, 2])\n",
    "x_one_hot = one_hot(x, vocab_size)\n",
    "print(x_one_hot)\n",
    "print(x_one_hot.shape)\n",
    "print(x_one_hot.sum(axis=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_eaelzjl",
    "id": "A01C821C29E54ECA95AF07E01A4997D6",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "我们每次采样的小批量的形状是（批量大小, 时间步数）。下面的函数将这样的小批量变换成数个形状为（批量大小, 词典大小）的矩阵，矩阵个数等于时间步数。也就是说，时间步$t$的输入为$\\boldsymbol{X}_t \\in \\mathbb{R}^{n \\times d}$，其中$n$为批量大小，$d$为词向量大小，即one-hot向量长度（词典大小）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "graffitiCellId": "id_961roi7",
    "id": "781B54CB28D741D9B8C2931ABD71F7F7",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 torch.Size([2, 1027])\n"
     ]
    }
   ],
   "source": [
    "def to_onehot(X, n_class):\n",
    "    return [one_hot(X[:, i], n_class) for i in range(X.shape[1])]\n",
    "\n",
    "X = torch.arange(10).view(2, 5)\n",
    "inputs = to_onehot(X, vocab_size)\n",
    "print(len(inputs), inputs[0].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_6nii7n3",
    "id": "323AB87BB02246F38BD4BB86219530E0",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 初始化模型参数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "graffitiCellId": "id_4667brq",
    "id": "C1F685ED1624479186E895EEECED6499",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size\n",
    "# num_inputs: d\n",
    "# num_hiddens: h, 隐藏单元的个数是超参数\n",
    "# num_outputs: q\n",
    "\n",
    "def get_params():\n",
    "    def _one(shape):\n",
    "        param = torch.zeros(shape, device=device, dtype=torch.float32)\n",
    "        nn.init.normal_(param, 0, 0.01)\n",
    "        return torch.nn.Parameter(param)\n",
    "\n",
    "    # 隐藏层参数\n",
    "    W_xh = _one((num_inputs, num_hiddens))\n",
    "    W_hh = _one((num_hiddens, num_hiddens))\n",
    "    b_h = torch.nn.Parameter(torch.zeros(num_hiddens, device=device))\n",
    "    # 输出层参数\n",
    "    W_hq = _one((num_hiddens, num_outputs))\n",
    "    b_q = torch.nn.Parameter(torch.zeros(num_outputs, device=device))\n",
    "    return (W_xh, W_hh, b_h, W_hq, b_q)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_ge2je0t",
    "id": "5C9E578391F04E988B0AF4415BB33767",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 定义模型\n",
    "\n",
    "函数`rnn`用循环的方式依次完成循环神经网络每个时间步的计算。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "graffitiCellId": "id_ffheq7o",
    "id": "E2C02FC273C543DE845D4CFD8F6B99EB",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def rnn(inputs, state, params):\n",
    "    # inputs和outputs皆为num_steps个形状为(batch_size, vocab_size)的矩阵\n",
    "    W_xh, W_hh, b_h, W_hq, b_q = params\n",
    "    H, = state\n",
    "    outputs = []\n",
    "    for X in inputs:\n",
    "        H = torch.tanh(torch.matmul(X, W_xh) + torch.matmul(H, W_hh) + b_h)\n",
    "        Y = torch.matmul(H, W_hq) + b_q\n",
    "        outputs.append(Y)\n",
    "    return outputs, (H,)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_ap3wbu6",
    "id": "6C4A4D9C506C4FD6953F9E0770A1D35A",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "函数init_rnn_state初始化隐藏变量，这里的返回值是一个元组。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "graffitiCellId": "id_ogd1cln",
    "id": "79F6F77218D44C20A99A85D8CBD26DD3",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def init_rnn_state(batch_size, num_hiddens, device):\n",
    "    return (torch.zeros((batch_size, num_hiddens), device=device), )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_cnjj602",
    "id": "006CB36276C74F5DBE8D4988915F99CB",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "做个简单的测试来观察输出结果的个数（时间步数），以及第一个时间步的输出层输出的形状和隐藏状态的形状。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "graffitiCellId": "id_5rof9df",
    "id": "DFFE1C2E29C9414A86EAB4D70A62A911",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([2, 5])\n",
      "256\n",
      "1027\n",
      "5 torch.Size([2, 1027])\n",
      "5 torch.Size([2, 1027])\n",
      "1 torch.Size([2, 256])\n",
      "1 torch.Size([2, 256])\n"
     ]
    }
   ],
   "source": [
    "print(X.shape)\n",
    "print(num_hiddens)\n",
    "print(vocab_size)\n",
    "state = init_rnn_state(X.shape[0], num_hiddens, device)\n",
    "inputs = to_onehot(X.to(device), vocab_size)\n",
    "params = get_params()\n",
    "outputs, state_new = rnn(inputs, state, params)\n",
    "print(len(inputs), inputs[0].shape)\n",
    "print(len(outputs), outputs[0].shape)\n",
    "print(len(state), state[0].shape)\n",
    "print(len(state_new), state_new[0].shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_zrzqvc3",
    "id": "7C5463AD4B364F0290B4E4A36A712481",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 裁剪梯度\n",
    "\n",
    "循环神经网络中较容易出现梯度衰减或梯度爆炸，这会导致网络几乎无法训练。裁剪梯度（clip gradient）是一种应对梯度爆炸的方法。假设我们把所有模型参数的梯度拼接成一个向量 $\\boldsymbol{g}$，并设裁剪的阈值是$\\theta$。裁剪后的梯度\n",
    "\n",
    "\n",
    "$$\n",
    " \\min\\left(\\frac{\\theta}{\\|\\boldsymbol{g}\\|}, 1\\right)\\boldsymbol{g}\n",
    "$$\n",
    "\n",
    "\n",
    "的$L_2$范数不超过$\\theta$。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "graffitiCellId": "id_ddfzc4y",
    "id": "4845C2DF302D45B68317E8C65B9691C0",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def grad_clipping(params, theta, device):\n",
    "    norm = torch.tensor([0.0], device=device)\n",
    "    for param in params:\n",
    "        norm += (param.grad.data ** 2).sum()\n",
    "    norm = norm.sqrt().item()\n",
    "    if norm > theta:\n",
    "        for param in params:\n",
    "            param.grad.data *= (theta / norm)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_qz5cf4d",
    "id": "8C548F77B1F642E1BE5C4758F2834AF7",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 定义预测函数\n",
    "\n",
    "以下函数基于前缀`prefix`（含有数个字符的字符串）来预测接下来的`num_chars`个字符。这个函数稍显复杂，其中我们将循环神经单元`rnn`设置成了函数参数，这样在后面小节介绍其他循环神经网络时能重复使用这个函数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "graffitiCellId": "id_e4mi857",
    "id": "228D7151704A45718C388511E8A0D1A6",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def predict_rnn(prefix, num_chars, rnn, params, init_rnn_state,\n",
    "                num_hiddens, vocab_size, device, idx_to_char, char_to_idx):\n",
    "    state = init_rnn_state(1, num_hiddens, device)\n",
    "    output = [char_to_idx[prefix[0]]]   # output记录prefix加上预测的num_chars个字符\n",
    "    for t in range(num_chars + len(prefix) - 1):\n",
    "        # 将上一时间步的输出作为当前时间步的输入\n",
    "        X = to_onehot(torch.tensor([[output[-1]]], device=device), vocab_size)\n",
    "        # 计算输出和更新隐藏状态\n",
    "        (Y, state) = rnn(X, state, params)\n",
    "        # 下一个时间步的输入是prefix里的字符或者当前的最佳预测字符\n",
    "        if t < len(prefix) - 1:\n",
    "            output.append(char_to_idx[prefix[t + 1]])\n",
    "        else:\n",
    "            output.append(Y[0].argmax(dim=1).item())\n",
    "    return ''.join([idx_to_char[i] for i in output])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_157mdwx",
    "id": "5F877F47755642A299DF44270D5B7C54",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "我们先测试一下`predict_rnn`函数。我们将根据前缀“分开”创作长度为10个字符（不考虑前缀长度）的一段歌词。因为模型参数为随机值，所以预测结果也是随机的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "graffitiCellId": "id_slr2lmi",
    "id": "753869000A07429384C791FD3131BEF8",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'分开濡时食提危踢拆田唱母'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predict_rnn('分开', 10, rnn, params, init_rnn_state, num_hiddens, vocab_size,\n",
    "            device, idx_to_char, char_to_idx)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_kasti5n",
    "id": "CECD70B6BFE348AD94C9B45DBEB604AE",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 困惑度\n",
    "\n",
    "我们通常使用困惑度（perplexity）来评价语言模型的好坏。回忆一下[“softmax回归”](../chapter_deep-learning-basics/softmax-regression.ipynb)一节中交叉熵损失函数的定义。困惑度是对交叉熵损失函数做指数运算后得到的值。特别地，\n",
    "\n",
    "* 最佳情况下，模型总是把标签类别的概率预测为1，此时困惑度为1；\n",
    "* 最坏情况下，模型总是把标签类别的概率预测为0，此时困惑度为正无穷；\n",
    "* 基线情况下，模型总是预测所有类别的概率都相同，此时困惑度为类别个数。\n",
    "\n",
    "显然，任何一个有效模型的困惑度必须小于类别个数。在本例中，困惑度必须小于词典大小`vocab_size`。\n",
    "\n",
    "### 定义模型训练函数\n",
    "\n",
    "跟之前章节的模型训练函数相比，这里的模型训练函数有以下几点不同：\n",
    "\n",
    "1. 使用困惑度评价模型。\n",
    "2. 在迭代模型参数前裁剪梯度。\n",
    "3. 对时序数据采用不同采样方法将导致隐藏状态初始化的不同。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "graffitiCellId": "id_yzrgxwe",
    "id": "9FE06ACC79564A21B427C2AB90AC5BAA",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,\n",
    "                          vocab_size, device, corpus_indices, idx_to_char,\n",
    "                          char_to_idx, is_random_iter, num_epochs, num_steps,\n",
    "                          lr, clipping_theta, batch_size, pred_period,\n",
    "                          pred_len, prefixes):\n",
    "    if is_random_iter:\n",
    "        data_iter_fn = d2l.data_iter_random\n",
    "    else:\n",
    "        data_iter_fn = d2l.data_iter_consecutive\n",
    "    params = get_params()\n",
    "    loss = nn.CrossEntropyLoss()\n",
    "\n",
    "    for epoch in range(num_epochs):\n",
    "        if not is_random_iter:  # 如使用相邻采样，在epoch开始时初始化隐藏状态\n",
    "            state = init_rnn_state(batch_size, num_hiddens, device)\n",
    "        l_sum, n, start = 0.0, 0, time.time()\n",
    "        data_iter = data_iter_fn(corpus_indices, batch_size, num_steps, device)\n",
    "        for X, Y in data_iter:\n",
    "            if is_random_iter:  # 如使用随机采样，在每个小批量更新前初始化隐藏状态\n",
    "                state = init_rnn_state(batch_size, num_hiddens, device)\n",
    "            else:  # 否则需要使用detach函数从计算图分离隐藏状态\n",
    "                for s in state:\n",
    "                    s.detach_()\n",
    "            # inputs是num_steps个形状为(batch_size, vocab_size)的矩阵\n",
    "            inputs = to_onehot(X, vocab_size)\n",
    "            # outputs有num_steps个形状为(batch_size, vocab_size)的矩阵\n",
    "            (outputs, state) = rnn(inputs, state, params)\n",
    "            # 拼接之后形状为(num_steps * batch_size, vocab_size)\n",
    "            outputs = torch.cat(outputs, dim=0)\n",
    "            # Y的形状是(batch_size, num_steps)，转置后再变成形状为\n",
    "            # (num_steps * batch_size,)的向量，这样跟输出的行一一对应\n",
    "            y = torch.flatten(Y.T)\n",
    "            # 使用交叉熵损失计算平均分类误差\n",
    "            l = loss(outputs, y.long())\n",
    "            \n",
    "            # 梯度清0\n",
    "            if params[0].grad is not None:\n",
    "                for param in params:\n",
    "                    param.grad.data.zero_()\n",
    "            l.backward()\n",
    "            grad_clipping(params, clipping_theta, device)  # 裁剪梯度\n",
    "            d2l.sgd(params, lr, 1)  # 因为误差已经取过均值，梯度不用再做平均\n",
    "            l_sum += l.item() * y.shape[0]\n",
    "            n += y.shape[0]\n",
    "\n",
    "        if (epoch + 1) % pred_period == 0:\n",
    "            print('epoch %d, perplexity %f, time %.2f sec' % (\n",
    "                epoch + 1, math.exp(l_sum / n), time.time() - start))\n",
    "            for prefix in prefixes:\n",
    "                print(' -', predict_rnn(prefix, pred_len, rnn, params, init_rnn_state,\n",
    "                    num_hiddens, vocab_size, device, idx_to_char, char_to_idx))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_abcvmn2",
    "id": "BC331C0942B549DD9CE8FF1D5FF1AA39",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 训练模型并创作歌词\n",
    "\n",
    "现在我们可以训练模型了。首先，设置模型超参数。我们将根据前缀“分开”和“不分开”分别创作长度为50个字符（不考虑前缀长度）的一段歌词。我们每过50个迭代周期便根据当前训练的模型创作一段歌词。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "graffitiCellId": "id_r49e5nv",
    "id": "528CB0DB2860481C8C803D377E5B5C89",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 250, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 50, 50, ['分开', '不分开']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_fvpvu53",
    "id": "867977FACDBE43528C0E17B7EC702F2C",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "下面采用随机采样训练模型并创作歌词。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "graffitiCellId": "id_xnnajux",
    "id": "B020BFA4A5A442D285BB1A7FC65BEA2E",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 50, perplexity 65.808092, time 0.78 sec\n",
      " - 分开 我想要这样 我不要再想 我不要再想 我不要再想 我不要再想 我不要再想 我不要再想 我不要再想 我\n",
      " - 不分开 别颗去 一颗两 三颗四 一颗四 三颗四 一颗四 一颗四 一颗四 一颗四 一颗四 一颗四 一颗四 一\n",
      "epoch 100, perplexity 9.794889, time 0.72 sec\n",
      " - 分开 一直在美留 谁在它停 在小村外的溪边 默默等  什么 旧你在依旧 我有儿有些瘦 世色我遇见你是一场\n",
      " - 不分开吗 我不能再想 我不 我不 我不 我不 我不 我不 我不 我不 我不 我不 我不 我不 我不 我不 \n",
      "epoch 150, perplexity 2.772557, time 0.80 sec\n",
      " - 分开 有直在不妥 有话它停留 蜥蝪横怕落 不爽就 旧怪堂 是属于依 心故之 的片段 有一些风霜 老唱盘 \n",
      " - 不分开吗 然后将过不 我慢 失些  如  静里回的太快 想通 却又再考倒我 说散 你想很久了吧?的我 从等\n",
      "epoch 200, perplexity 1.601744, time 0.73 sec\n",
      " - 分开 那只都它满在我面妈 捏成你的形状啸而过 或愿说在后能 让梭时忆对着轻轻 我想就这样牵着你的手不放开\n",
      " - 不分开期 然后将过去 慢慢温习 让我爱上你 那场悲剧 是你完美演出的一场戏 宁愿心碎哭泣 再狠狠忘记 不是\n",
      "epoch 250, perplexity 1.323342, time 0.78 sec\n",
      " - 分开 出愿段的哭咒的天蛦丘好落 拜托当血穿永杨一定的诗篇 我给你的爱写在西元前 深埋在美索不达米亚平原 \n",
      " - 不分开扫把的胖女巫 用拉丁文念咒语啦啦呜 她养的黑猫笑起来像哭 啦啦啦呜 我来了我 在我感外的溪边河口默默\n"
     ]
    }
   ],
   "source": [
    "train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,\n",
    "                      vocab_size, device, corpus_indices, idx_to_char,\n",
    "                      char_to_idx, True, num_epochs, num_steps, lr,\n",
    "                      clipping_theta, batch_size, pred_period, pred_len,\n",
    "                      prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_t650z1s",
    "id": "CC35E4A71367440F8EBB8C8F13F50677",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "接下来采用相邻采样训练模型并创作歌词。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "graffitiCellId": "id_5cubvww",
    "id": "60A46F92EC144D4A81FFC0D73850D275",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 50, perplexity 60.294393, time 0.74 sec\n",
      " - 分开 我想要你想 我不要再想 我不要再想 我不要再想 我不要再想 我不要再想 我不要再想 我不要再想 我\n",
      " - 不分开 我想要你 你有了 别不我的可爱女人 坏坏的让我疯狂的可爱女人 坏坏的让我疯狂的可爱女人 坏坏的让我\n",
      "epoch 100, perplexity 7.141162, time 0.72 sec\n",
      " - 分开 我已要再爱 我不要再想 我不 我不 我不要再想 我不 我不 我不要 爱情我的见快就像龙卷风 离能开\n",
      " - 不分开柳 你天黄一个棍 后知哈兮 快使用双截棍 哼哼哈兮 快使用双截棍 哼哼哈兮 快使用双截棍 哼哼哈兮 \n",
      "epoch 150, perplexity 2.090277, time 0.73 sec\n",
      " - 分开 我已要这是你在著 不想我都做得到 但那个人已经不是我 没有你在 我却多难熬  没有你在我有多难熬多\n",
      " - 不分开觉 你已经离 我想再好 这样心中 我一定带我 我的完空 不你是风 一一彩纵 在人心中 我一定带我妈走\n",
      "epoch 200, perplexity 1.305391, time 0.77 sec\n",
      " - 分开 我已要这样牵看你的手 它一定实现它一定像现 载著你 彷彿载著阳光 不管到你留都是晴天 蝴蝶自在飞力\n",
      " - 不分开觉 你已经离开我 不知不觉 我跟了这节奏 后知后觉 又过了一个秋 后知后觉 我该好好生活 我该好好生\n",
      "epoch 250, perplexity 1.230800, time 0.79 sec\n",
      " - 分开 我不要 是你看的太快了悲慢 担心今手身会大早 其么我也睡不着  昨晚梦里你来找 我才  原来我只想\n",
      " - 不分开觉 你在经离开我 不知不觉 你知了有节奏 后知后觉 后知了一个秋 后知后觉 我该好好生活 我该好好生\n"
     ]
    }
   ],
   "source": [
    "train_and_predict_rnn(rnn, get_params, init_rnn_state, num_hiddens,\n",
    "                      vocab_size, device, corpus_indices, idx_to_char,\n",
    "                      char_to_idx, False, num_epochs, num_steps, lr,\n",
    "                      clipping_theta, batch_size, pred_period, pred_len,\n",
    "                      prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_k40p6v8",
    "id": "868B10D9B4DE4D0B93E79F5746A49D47",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "## 循环神经网络的简介实现\n",
    "\n",
    "### 定义模型\n",
    "\n",
    "我们使用Pytorch中的`nn.RNN`来构造循环神经网络。在本节中，我们主要关注`nn.RNN`的以下几个构造函数参数：\n",
    "\n",
    "* `input_size` - The number of expected features in the input x\n",
    "* `hidden_size` – The number of features in the hidden state h\n",
    "* `nonlinearity` – The non-linearity to use. Can be either 'tanh' or 'relu'. Default: 'tanh'\n",
    "* `batch_first` – If True, then the input and output tensors are provided as (batch_size, num_steps, input_size). Default: False\n",
    "\n",
    "这里的`batch_first`决定了输入的形状，我们使用默认的参数`False`，对应的输入形状是 (num_steps, batch_size, input_size)。\n",
    "\n",
    "`forward`函数的参数为：\n",
    "\n",
    "* `input` of shape (num_steps, batch_size, input_size): tensor containing the features of the input sequence. \n",
    "* `h_0` of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. If the RNN is bidirectional, num_directions should be 2, else it should be 1.\n",
    "\n",
    "`forward`函数的返回值是：\n",
    "\n",
    "* `output` of shape (num_steps, batch_size, num_directions * hidden_size): tensor containing the output features (h_t) from the last layer of the RNN, for each t.\n",
    "* `h_n` of shape (num_layers * num_directions, batch_size, hidden_size): tensor containing the hidden state for t = num_steps.\n",
    "\n",
    "现在我们构造一个`nn.RNN`实例，并用一个简单的例子来看一下输出的形状。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "graffitiCellId": "id_j3cpkcl",
    "id": "0299EF9E9126417B80153A137538E01E",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "torch.Size([35, 2, 256]) torch.Size([1, 2, 256])\n"
     ]
    }
   ],
   "source": [
    "rnn_layer = nn.RNN(input_size=vocab_size, hidden_size=num_hiddens)\n",
    "num_steps, batch_size = 35, 2\n",
    "X = torch.rand(num_steps, batch_size, vocab_size)\n",
    "state = None\n",
    "Y, state_new = rnn_layer(X, state)\n",
    "print(Y.shape, state_new.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_m47aq8s",
    "id": "069F7F5EE53E47FA9E67B386F372D166",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "我们定义一个完整的基于循环神经网络的语言模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "graffitiCellId": "id_syy2qdo",
    "id": "9B2540FE03B44485818E407213E44E82",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "class RNNModel(nn.Module):\n",
    "    def __init__(self, rnn_layer, vocab_size):\n",
    "        super(RNNModel, self).__init__()\n",
    "        self.rnn = rnn_layer\n",
    "        self.hidden_size = rnn_layer.hidden_size * (2 if rnn_layer.bidirectional else 1) \n",
    "        self.vocab_size = vocab_size\n",
    "        self.dense = nn.Linear(self.hidden_size, vocab_size)\n",
    "\n",
    "    def forward(self, inputs, state):\n",
    "        # inputs.shape: (batch_size, num_steps)\n",
    "        X = to_onehot(inputs, vocab_size)\n",
    "        X = torch.stack(X)  # X.shape: (num_steps, batch_size, vocab_size)\n",
    "        hiddens, state = self.rnn(X, state)\n",
    "        hiddens = hiddens.view(-1, hiddens.shape[-1])  # hiddens.shape: (num_steps * batch_size, hidden_size)\n",
    "        output = self.dense(hiddens)\n",
    "        return output, state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_soot8nz",
    "id": "288D99C0B51F45659BB0F39C2B5AAD9B",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "类似的，我们需要实现一个预测函数，与前面的区别在于前向计算和初始化隐藏状态。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "graffitiCellId": "id_dkebt7t",
    "id": "470CA7EEF6C2443980C3D327EB4BAD73",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def predict_rnn_pytorch(prefix, num_chars, model, vocab_size, device, idx_to_char,\n",
    "                      char_to_idx):\n",
    "    state = None\n",
    "    output = [char_to_idx[prefix[0]]]  # output记录prefix加上预测的num_chars个字符\n",
    "    for t in range(num_chars + len(prefix) - 1):\n",
    "        X = torch.tensor([output[-1]], device=device).view(1, 1)\n",
    "        (Y, state) = model(X, state)  # 前向计算不需要传入模型参数\n",
    "        if t < len(prefix) - 1:\n",
    "            output.append(char_to_idx[prefix[t + 1]])\n",
    "        else:\n",
    "            output.append(Y.argmax(dim=1).item())\n",
    "    return ''.join([idx_to_char[i] for i in output])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_6dx4k76",
    "id": "A1009A6DA48749D883D7DEE75F8B55EF",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "使用权重为随机值的模型来预测一次。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "graffitiCellId": "id_dovnvrc",
    "id": "7000F425557A4047A9D7B0BD446C4B48",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'分开胸呵以轮轮轮轮轮轮轮'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = RNNModel(rnn_layer, vocab_size).to(device)\n",
    "predict_rnn_pytorch('分开', 10, model, vocab_size, device, idx_to_char, char_to_idx)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_3bm44z0",
    "id": "F3BA8B41B5E14E2191674147D2022A39",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "接下来实现训练函数，这里只使用了相邻采样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "graffitiCellId": "id_kqdlzc9",
    "id": "C6B0157AB1964E14AD52BFC3B4E8ACCE",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                                corpus_indices, idx_to_char, char_to_idx,\n",
    "                                num_epochs, num_steps, lr, clipping_theta,\n",
    "                                batch_size, pred_period, pred_len, prefixes):\n",
    "    loss = nn.CrossEntropyLoss()\n",
    "    optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n",
    "    model.to(device)\n",
    "    for epoch in range(num_epochs):\n",
    "        l_sum, n, start = 0.0, 0, time.time()\n",
    "        data_iter = d2l.data_iter_consecutive(corpus_indices, batch_size, num_steps, device) # 相邻采样\n",
    "        state = None\n",
    "        for X, Y in data_iter:\n",
    "            if state is not None:\n",
    "                # 使用detach函数从计算图分离隐藏状态\n",
    "                if isinstance (state, tuple): # LSTM, state:(h, c)  \n",
    "                    state[0].detach_()\n",
    "                    state[1].detach_()\n",
    "                else: \n",
    "                    state.detach_()\n",
    "            (output, state) = model(X, state) # output.shape: (num_steps * batch_size, vocab_size)\n",
    "            y = torch.flatten(Y.T)\n",
    "            l = loss(output, y.long())\n",
    "            \n",
    "            optimizer.zero_grad()\n",
    "            l.backward()\n",
    "            grad_clipping(model.parameters(), clipping_theta, device)\n",
    "            optimizer.step()\n",
    "            l_sum += l.item() * y.shape[0]\n",
    "            n += y.shape[0]\n",
    "        \n",
    "\n",
    "        if (epoch + 1) % pred_period == 0:\n",
    "            print('epoch %d, perplexity %f, time %.2f sec' % (\n",
    "                epoch + 1, math.exp(l_sum / n), time.time() - start))\n",
    "            for prefix in prefixes:\n",
    "                print(' -', predict_rnn_pytorch(\n",
    "                    prefix, pred_len, model, vocab_size, device, idx_to_char,\n",
    "                    char_to_idx))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "graffitiCellId": "id_0ejh2ag",
    "id": "E271EA2BA38045BF93AD1CD9484A3194",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "训练模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "graffitiCellId": "id_kn2ynjc",
    "id": "1FC86D37312346418E960DE255315FC0",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 50, perplexity 9.405654, time 0.52 sec\n",
      " - 分开始一起 三步四步望著天 看星星 一颗两颗三颗四颗 连成线背著背默默许下心愿  一枝杨柳 你的那我 在\n",
      " - 不分开 爱情你的手 一人的老斑鸠 腿短毛不多 快使用双截棍 哼哼哈兮 快使用双截棍 哼哼哈兮 快使用双截棍\n",
      "epoch 100, perplexity 1.255020, time 0.54 sec\n",
      " - 分开 我人了的屋我 一定令它心仪的母斑鸠 爱像一阵风 吹完美主  这样 还人的太快就是学怕眼口让我碰恨这\n",
      " - 不分开不想我多的脑袋有问题 随便说说 其实我早已经猜透看透不想多说 只是我怕眼泪撑不住 不懂 你的黑色幽默\n",
      "epoch 150, perplexity 1.064527, time 0.53 sec\n",
      " - 分开 我轻外的溪边 默默在一心抽离 有话不知不觉 一场悲剧 我对不起 藤蔓植物的爬满了伯爵的坟墓 古堡里\n",
      " - 不分开不想不多的脑 有教堂有你笑 我有多烦恼  没有你烦 有有样 别怪走 快后悔没说你 我不多难熬 我想就\n",
      "epoch 200, perplexity 1.033074, time 0.53 sec\n",
      " - 分开 我轻外的溪边 默默在一心向昏 的愿  古无着我只能 一个黑远 这想太久 这样我 不要再是你打我妈妈\n",
      " - 不分开你只会我一起睡著 样 娘子却只想你和汉堡 我想要你的微笑每天都能看到  我知道这里很美但家乡的你更美\n",
      "epoch 250, perplexity 1.047890, time 0.68 sec\n",
      " - 分开 我轻多的漫 却已在你人演  想要再直你 我想要这样牵着你的手不放开 爱可不可以简简单单没有伤害 你\n",
      " - 不分开不想不多的假  已无能为力再提起 决定中断熟悉 然后在这里 不限日期 然后将过去 慢慢温习 让我爱上\n"
     ]
    }
   ],
   "source": [
    "num_epochs, batch_size, lr, clipping_theta = 250, 32, 1e-3, 1e-2\n",
    "pred_period, pred_len, prefixes = 50, 50, ['分开', '不分开']\n",
    "train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                            corpus_indices, idx_to_char, char_to_idx,\n",
    "                            num_epochs, num_steps, lr, clipping_theta,\n",
    "                            batch_size, pred_period, pred_len, prefixes)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
